<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="产品名称">
          <el-input v-model="queryParams.name" placeholder="请输入产品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="产品编码">
          <el-input v-model="queryParams.code" placeholder="请输入产品编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="产品类型">
          <el-select v-model="queryParams.type" placeholder="请选择产品类型" clearable>
            <el-option label="套餐" value="package"></el-option>
            <el-option label="单品" value="single"></el-option>
            <el-option label="服务" value="service"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="在售" :value="1"></el-option>
            <el-option label="下架" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <el-card class="box-card">
      <div class="clearfix">
        <el-button type="primary" @click="handleAdd">新增产品</el-button>
      </div>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="productList"
        border
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="product_id" label="ID" width="80"></el-table-column>
        <el-table-column prop="code" label="产品编码" width="120"></el-table-column>
        <el-table-column prop="name" label="产品名称"></el-table-column>
        <el-table-column prop="type" label="产品类型" width="100">
          <template #default="scope">
            {{ typeMap[scope.row.type] }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="标准价格" width="120">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="black_card_price" label="黑卡价格" width="120">
          <template #default="scope">
            ¥{{ scope.row.black_card_price }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '在售' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_featured" label="特色产品" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_featured === 1 ? 'warning' : ''">
              {{ scope.row.is_featured === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              type="text" 
              @click="handleChangeStatus(scope.row)"
              :class="{ 'success-btn': scope.row.status === 0 }"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button type="text" class="delete-btn" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :current-page="queryParams.page"
          :page-size="queryParams.limit"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="产品类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择产品类型">
            <el-option label="套餐" value="package"></el-option>
            <el-option label="单品" value="single"></el-option>
            <el-option label="服务" value="service"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品分类" prop="category_id">
          <el-cascader
            v-model="form.category_id"
            :options="categoryOptions"
            :props="{
              value: 'category_id',
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择产品分类"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="景区" prop="scenic_spot_id">
          <el-select v-model="form.scenic_spot_id" placeholder="请选择景区">
            <el-option
              v-for="item in scenicSpotOptions"
              :key="item.scenic_spot_id"
              :label="item.name"
              :value="item.scenic_spot_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="标准价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="黑卡价格" prop="black_card_price">
          <el-input-number v-model="form.black_card_price" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="原价" prop="original_price">
          <el-input-number v-model="form.original_price" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="有效期(天)" prop="validity_period">
          <el-input-number v-model="form.validity_period" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="预订人数限制" prop="min_people">
          <el-col :span="11">
            <el-input-number v-model="form.min_people" :min="1" placeholder="最小预订人数"></el-input-number>
          </el-col>
          <el-col :span="2" class="text-center">-</el-col>
          <el-col :span="11">
            <el-input-number v-model="form.max_people" :min="1" placeholder="最大预订人数"></el-input-number>
          </el-col>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否特色产品" prop="is_featured">
          <el-switch v-model="form.is_featured" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="产品图片" prop="images">
          <el-upload
            v-model:file-list="fileList"
            action="/app/ky_black/admin/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :headers="{
              'X-Requested-With': 'XMLHttpRequest'
            }"
            :data="{
              type: 'scenic_product'
            }"
            accept="image/jpeg,image/png,image/gif"
            :limit="5"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/png/gif 格式，单个文件不超过 2MB
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="previewVisible">
            <img w-full :src="previewUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="产品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="6"
            placeholder="请输入产品描述"
          />
        </el-form-item>
        <el-form-item label="产品特色" prop="features">
          <el-input
            v-model="form.features"
            type="textarea"
            :rows="6"
            placeholder="请输入产品特色"
          />
        </el-form-item>
        <el-form-item label="包含项目" prop="include_items">
          <el-input
            v-model="form.include_items"
            type="textarea"
            :rows="6"
            placeholder="请输入包含项目"
          />
        </el-form-item>
        <el-form-item label="不包含项目" prop="exclude_items">
          <el-input
            v-model="form.exclude_items"
            type="textarea"
            :rows="6"
            placeholder="请输入不包含项目"
          />
        </el-form-item>
        <el-form-item label="使用须知" prop="notice">
          <el-input
            v-model="form.notice"
            type="textarea"
            :rows="6"
            placeholder="请输入使用须知"
          />
        </el-form-item>
        <el-form-item label="取消规则" prop="cancel_rule">
          <el-input
            v-model="form.cancel_rule"
            type="textarea"
            :rows="6"
            placeholder="请输入取消规则"
          />
        </el-form-item>
        <el-form-item label="预约说明" prop="reservation_notice">
          <el-input
            v-model="form.reservation_notice"
            type="textarea"
            :rows="6"
            placeholder="请输入预约说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog v-model="previewVisible">
      <img width="100%" :src="previewUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

export default {
  name: 'ScenicProduct',
  components: {
    Plus
  },
  setup() {
    // 常量
    const typeMap = {
      package: '套餐',
      single: '单品',
      service: '服务'
    }

    // 查询参数
    const queryParams = reactive({
      page: 1,
      limit: 10,
      name: '',
      code: '',
      type: '',
      status: ''
    })

    // 表格数据
    const loading = ref(false)
    const productList = ref([])
    const total = ref(0)
    const categoryOptions = ref([])
    const scenicSpotOptions = ref([])

    // 弹窗数据
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const formRef = ref(null)
    const form = reactive({
      product_id: undefined,
      type: '',
      category_id: '',
      scenic_spot_id: '',
      name: '',
      price: 0,
      black_card_price: 0,
      original_price: 0,
      validity_period: 0,
      min_people: 1,
      max_people: null,
      sort: 0,
      status: 1,
      is_featured: 0,
      images: [],
      description: '',
      features: '',
      include_items: '',
      exclude_items: '',
      notice: '',
      cancel_rule: '',
      reservation_notice: ''
    })

    // 图片上传
    const fileList = ref([])
    const previewVisible = ref(false)
    const previewUrl = ref('')

    // 表单校验规则
    const rules = {
      type: [{ required: true, message: '请选择产品类型', trigger: 'change' }],
      category_id: [{ required: true, message: '请选择产品分类', trigger: 'change' }],
      scenic_spot_id: [{ required: true, message: '请选择景区', trigger: 'change' }],
      name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
      price: [{ required: true, message: '请输入标准价格', trigger: 'blur' }],
      black_card_price: [{ required: true, message: '请输入黑卡价格', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }

    // 获取产品列表
    const getList = async () => {
      loading.value = true
      try {
        const res = await request({
          url: '/scenic-product/list',
          method: 'get',
          params: queryParams
        })
        if (res.code === 0) {
          productList.value = res.data.list
          total.value = res.data.total
        }
      } catch (error) {
        console.error('获取产品列表失败:', error)
      }
      loading.value = false
    }

    // 获取分类选项
    const getCategoryOptions = async () => {
      try {
        const res = await request({
          url: '/scenic-product/options',
          method: 'get'
        })
        if (res.code === 0) {
          categoryOptions.value = res.data.categories || []
        }
      } catch (error) {
        console.error('获取分类选项失败:', error)
      }
    }

    // 获取景区选项
    const getScenicSpotOptions = async () => {
      try {
        const res = await request({
          url: '/scenic-product/options',
          method: 'get'
        })
        if (res.code === 0) {
          scenicSpotOptions.value = res.data.scenic_spots || []
        }
      } catch (error) {
        console.error('获取景区选项失败:', error)
      }
    }

    // 查询操作
    const handleQuery = () => {
      queryParams.page = 1
      getList()
    }

    // 重置查询
    const resetQuery = () => {
      queryParams.name = ''
      queryParams.code = ''
      queryParams.type = ''
      queryParams.status = ''
      handleQuery()
    }

    // 新增产品
    const handleAdd = () => {
      dialogTitle.value = '新增产品'
      Object.assign(form, {
        product_id: undefined,
        type: '',
        category_id: '',
        scenic_spot_id: '',
        name: '',
        price: 0,
        black_card_price: 0,
        original_price: 0,
        validity_period: 0,
        min_people: 1,
        max_people: null,
        sort: 0,
        status: 1,
        is_featured: 0,
        images: [],
        description: '',
        features: '',
        include_items: '',
        exclude_items: '',
        notice: '',
        cancel_rule: '',
        reservation_notice: ''
      })
      fileList.value = []
      dialogVisible.value = true
    }

    // 编辑产品
    const handleEdit = (row) => {
      dialogTitle.value = '编辑产品'
      Object.assign(form, row)
      // 处理图片列表
      fileList.value = (row.images || []).map(url => {
        const fullUrl = url.startsWith('http') ? url : 'http://127.0.0.1:8787' + url
        return {
          url: fullUrl,
          name: url.substring(url.lastIndexOf('/') + 1)
        }
      })
      dialogVisible.value = true
    }

    // 删除产品
    const handleDelete = (row) => {
      ElMessageBox.confirm('确认要删除该产品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await request({
              url: '/scenic_product/delete',
              method: 'post',
              data: { product_id: row.product_id }
            })
            if (res.code === 0) {
              ElMessage.success('删除成功')
              getList()
            } else {
              ElMessage.error(res.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除产品失败:', error)
            ElMessage.error('删除失败')
          }
        })
        .catch(() => {})
    }

    // 修改状态
    const handleChangeStatus = async (row) => {
      try {
        const res = await request({
          url: '/scenic_product/status',
          method: 'post',
          data: {
            product_id: row.product_id,
            status: row.status === 1 ? 0 : 1
          }
        })
        if (res.code === 0) {
          ElMessage.success(row.status === 1 ? '下架成功' : '上架成功')
          getList()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('修改状态失败:', error)
        ElMessage.error('操作失败')
      }
    }

    // 图片上传相关
    const handlePictureCardPreview = (uploadFile) => {
      previewUrl.value = uploadFile.url
      previewVisible.value = true
    }

    const handleRemove = (uploadFile) => {
      // 从表单的图片数组中移除
      const relativeUrl = uploadFile.url.replace('http://127.0.0.1:8787', '')
      form.images = (form.images || []).filter(url => url !== relativeUrl)
    }

    const handleUploadSuccess = (response, uploadFile) => {
      if (response.code === 0) {
        // 设置完整的URL
        const fullUrl = response.data.url.startsWith('http') 
          ? response.data.url 
          : 'http://127.0.0.1:8787' + response.data.url
        uploadFile.url = fullUrl
        // 更新表单的图片数组
        form.images = form.images || []
        form.images.push(response.data.url)
        ElMessage.success('上传成功')
      } else {
        ElMessage.error(response.msg || '上传失败')
        fileList.value = fileList.value.filter(file => file.uid !== uploadFile.uid)
      }
    }

    const beforeUpload = (file) => {
      const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        ElMessage.error('只能上传 jpg/png/gif 格式的图片！')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB！')
        return false
      }
      return true
    }

    // 提交表单
    const submitForm = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const url = form.product_id
              ? '/scenic_product/edit'
              : '/scenic_product/add'
            
            // 处理提交数据
            const submitData = {
              ...form,
              // 如果 category_id 是数组，取最后一个值
              category_id: Array.isArray(form.category_id) ? form.category_id[form.category_id.length - 1] : form.category_id,
              // 确保 images 是字符串数组
              images: Array.isArray(form.images) ? form.images : [],
              // 确保数字字段为数字类型
              price: Number(form.price),
              black_card_price: Number(form.black_card_price),
              original_price: Number(form.original_price),
              validity_period: Number(form.validity_period),
              min_people: Number(form.min_people),
              max_people: form.max_people ? Number(form.max_people) : null,
              sort: Number(form.sort),
              status: Number(form.status),
              is_featured: Number(form.is_featured),
              scenic_spot_id: Number(form.scenic_spot_id)
            }

            const res = await request({
              url,
              method: 'post',
              data: submitData
            })
            if (res.code === 0) {
              ElMessage.success(form.product_id ? '编辑成功' : '添加成功')
              dialogVisible.value = false
              getList()
            } else {
              ElMessage.error(res.msg || (form.product_id ? '编辑失败' : '添加失败'))
            }
          } catch (error) {
            console.error(form.product_id ? '编辑产品失败:' : '添加产品失败:', error)
            ElMessage.error(form.product_id ? '编辑失败' : '添加失败')
          }
        }
      })
    }

    // 分页操作
    const handleSizeChange = (val) => {
      queryParams.limit = val
      getList()
    }

    const handleCurrentChange = (val) => {
      queryParams.page = val
      getList()
    }

    onMounted(() => {
      getList()
      getCategoryOptions()
      getScenicSpotOptions()
    })

    return {
      typeMap,
      queryParams,
      loading,
      productList,
      total,
      categoryOptions,
      scenicSpotOptions,
      dialogVisible,
      dialogTitle,
      formRef,
      form,
      rules,
      fileList,
      previewVisible,
      previewUrl,
      handleQuery,
      resetQuery,
      handleAdd,
      handleEdit,
      handleDelete,
      handleChangeStatus,
      handlePictureCardPreview,
      handleRemove,
      handleUploadSuccess,
      beforeUpload,
      submitForm,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.search-wrapper {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.delete-btn {
  color: #F56C6C;
}
.success-btn {
  color: #67C23A;
}
.text-center {
  text-align: center;
  line-height: 32px;
}
</style> 